/*
 * MaxSonarEZ1.java
 *
 * Created on November 7, 2006, 10:31 AM
 *
 * Copyright 2006 , Sun Microsystems
 * All Rights Reserved
 *
 */

package com.iaroc.irobot.sample;

import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.EDemoBoard;
import com.sun.spot.sensorboard.io.IOutputPin;
import com.sun.spot.sensorboard.io.IScalarInput;
import com.sun.spot.sensorboard.io.PinDescriptor;
import com.sun.spot.util.Utils;
import java.io.IOException;

/**
 *
 * @author arshan (mods by Poorna)
 */
public class MaxSonarEZ1 {
    
    IScalarInput analogPin  = null;
    IOutputPin   triggerPin = null;
    EDemoBoard   demoBoard = EDemoBoard.getInstance();
    int running_avg = 0;
    // keep the cached distance reading out here so that if there is an exception
    // during aquisition the part will return the previous reading again
    private int current = 0;
    
    /**
     * Creates a new instance of MaxSonarEZ1
     */
    public MaxSonarEZ1(int aPin) {
        analogPin = demoBoard.getScalarInputs()[aPin];
        Utils.sleep(250);
    }

    /**
     * Creates a new instance of MaxSonarEZ1 that uses a trigger get the reading *
     */
    public MaxSonarEZ1(PinDescriptor aPin , PinDescriptor tPin) {
        //analogPin  = EDemoBoard.getInstance(aPin);
        analogPin = demoBoard.getScalarInputs()[aPin.toInteger()];
        //triggerPin = EDemoBoard.getInstance().bindOutputPin(tPin);
        triggerPin = demoBoard.getOutputPins()[tPin.toInteger()];
        if (triggerPin != null) {
            triggerPin.setLow();
        }
        Utils.sleep(250);
    }
    
    /* return measure of distance in inches */
    public int getDistance() {
        
        if ( triggerPin != null ) {
            triggerPin.setHigh();
            triggerPin.setLow();
            Utils.sleep(50);
        }
            
        try {
            current = analogPin.getValue();
            //System.out.println("Current: " + current);
        } catch (IOException ex) {
            error("bad value from sensor"); // not the most informative change it later
        }

        // function for voltage from ADC is
        // Vcc = 2.7V (==5v?)
        // LSB = Vcc/1024 = 2.7/1024 = 0.00263671875 (==0.0048828125)
        // voltage = (adcValue*LSB*1000)mV = (current*2.63671875)mV (==current*4.8828125?)
        // be careful of how this is rounding
        //int mV = (int)((float)current*2.63671875f);
        int mV = (int)((float)current*4.8828125f);
        //System.out.println("mV: " + mV);
        
        // spec sheet claims 10mV per inch
        return current;// mV/10; // return inches
    }
    
    private void error(String txt) {
        System.out.println("[MaxBotixEZ1] ERROR : " + txt);
    }
}
